package com.satan.juc.demo11;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockDowngradeExample {
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final ReentrantReadWriteLock.ReadLock readLock = rwLock.readLock();
    private final ReentrantReadWriteLock.WriteLock writeLock = rwLock.writeLock();
    private int data = 0;

    public void writeData() {
        writeLock.lock();
        try {
            data++;
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + "写入数据：" + data);
            // 在释放写锁之前获取读锁，进行锁降级
            readLock.lock();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放写锁，但仍持有读锁
            writeLock.unlock();
        }
        try {
            // 模拟读取数据的操作
            System.out.println(Thread.currentThread().getName() + "读取数据: " + data);
        } finally {
            // 释放读锁
            readLock.unlock();
        }
    }

    public void readData() {
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读取数据: " + data);
        } finally {
            readLock.unlock();
        }
    }

    public static void main(String[] args) {
        LockDowngradeExample example = new LockDowngradeExample();
        // 写线程
        for (int i = 0; i < 1; i++) {
            new Thread(example::writeData, "写线程"+i).start();
        }
        // 读线程
        for (int i = 0; i < 10; i++) {
            new Thread(example::readData, "读线程" + i).start();
        }
    }
}
